package com.htandroid.htandroid.aty;

import android.Manifest;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.provider.Settings;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;

import com.ab.soap.AbSoapListener;
import com.ab.soap.AbSoapParams;
import com.ab.soap.AbSoapUtil;
import com.ab.task.AbTask;
import com.ab.task.AbTaskItem;
import com.ab.task.AbTaskObjectListener;
import com.ab.util.AbDialogUtil;
import com.ab.util.AbToastUtil;
import com.ab.view.ioc.AbIocView;
import com.google.gson.Gson;
import com.htandroid.htandroid.R;
import com.htandroid.htandroid.global.MyApplication;
import com.htandroid.htandroid.sys.InstorageURL;
import com.htandroid.htandroid.sys.User;
import com.htandroid.reconstitute.base.ConstanceHeTai;
import com.htandroid.reconstitute.base.ConstanceHttp;
import com.htandroid.reconstitute.entity.LoginBean;
import com.htandroid.reconstitute.http.OkHttpRequestUtils;
import com.htandroid.reconstitute.utils.SpUtil;
import com.htandroid.reconstitute.utils.ToastUtil;
import com.htandroid.reconstitute.utils.permission.EasyPermission;
import com.htandroid.reconstitute.utils.permission.PermissionResultCallBack;
import com.mob.MobSDK;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

import cn.jpush.android.api.JPushInterface;
import okhttp3.Call;

import static com.htandroid.htandroid.constance.ConstanceServer.BaseUrl_New;

/**
 * Created by lkp on 2015/11/26.
 */
public class Login extends MyBaseActivity implements PermissionResultCallBack {
    private String mStr_name = null;
    private String mStr_pwd = null;
    private MyApplication application;
    private AbSoapUtil mAbSoapUtil = null;
    private String registrationId = null;

    @AbIocView(id = R.id.et_username)
    EditText username;
    @AbIocView(id = R.id.et_pwd)
    EditText pwd;
    @AbIocView(id = R.id.remember_pwd)
    CheckBox rem_pw;
    @AbIocView(id = R.id.btn_ss, click = "btnClick")
    TextView btn_ss;
    @AbIocView(id = R.id.btn_login, click = "btnClick")
    TextView loginBtn;
    @AbIocView(id = R.id.version_tv)
    TextView version_tv;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setAbContentView(R.layout.layout_login);
        titleBar.setBackgroundColor(Color.parseColor("#f1f1f1"));
        application = (MyApplication) abApplication;
        //获取Http工具类
        mAbSoapUtil = AbSoapUtil.getInstance(this);
        mAbSoapUtil.setTimeout(10000);
//        initCheckPermission();
        initdata();
        MobSDK.init(this);
        initId();
    }

    private void initCheckPermission() {
        String[] arr_permision = new String[]{
                Manifest.permission.READ_EXTERNAL_STORAGE,
                Manifest.permission.WRITE_EXTERNAL_STORAGE};
        //根据列出的权限分次获取敏感权限
        EasyPermission.with(this).code(ConstanceHeTai.REQUEST_CODE).permissions(arr_permision).request();
    }

    public void initId() {
        if (application.getRegistrationId() == null || application.getRegistrationId() == "" ||
                "null".equalsIgnoreCase(application.getRegistrationId())) {
            JPushInterface.setDebugMode(true);
            JPushInterface.init(getApplicationContext());
            if (JPushInterface.isPushStopped(getApplicationContext())) {
                JPushInterface.resumePush(getApplicationContext());//恢复极光推送
            }
            registrationId = JPushInterface.getRegistrationID(this);
            application.setRegistrationId(registrationId);
        } else {

        }
    }

    public void btnClick(View v) {
        Intent intent = null;
        switch (v.getId()) {
            case R.id.btn_ss:
                intent = new Intent(getApplicationContext(), ServerSettings.class);
                startActivity(intent);
                break;
            case R.id.btn_login:
                mStr_name = username.getText().toString();
                mStr_pwd = pwd.getText().toString();


                if (TextUtils.isEmpty(mStr_name)) {
                    AbToastUtil.showToast(Login.this, R.string.isEmpty);
                    username.setFocusable(true);
                    username.requestFocus();
                    return;
                }
                if (TextUtils.isEmpty(mStr_pwd)){
                    ToastUtil.showToast("请输入密码");
                    return;
                }
                String string = SpUtil.getString(Login.this, ConstanceHeTai.login_server_address);
                if (TextUtils.isEmpty(string)){
                    ToastUtil.showToast("请配置服务器地址");
                    return;
                }

                Map<String,String> map=new LinkedHashMap<>();
                map.put("user",mStr_name);
                map.put("psw",mStr_pwd);

                login(map,ConstanceHttp.base_url+string+ConstanceHttp.sysabout_user_login);


                if (rem_pw.isChecked()) {
                    //记住用户名,并且保存密码
                    SharedPreferences.Editor editor = application.mSharedPreferences.edit();
                    editor.putBoolean("LOGIN_ISCHECK", true);

                    editor.putString("LOGIN_USER_NAME", mStr_name);
                    editor.putString("LOGIN_PASSWORD", mStr_pwd);
                    editor.commit();

                }


//                abLogin();
                break;
        }
    }

    private void login(Map<String,String> mParams,String mUrl) {
        OkHttpUtils.post().url(mUrl).params(mParams).build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                String message = e.getMessage();
                ToastUtil.showToast("服务异常-"+message);

            }

            @Override
            public void onResponse(String response, int id) {
                String string = response.toString();
                try {
                    Gson gson=new Gson();
                    LoginBean loginBean = gson.fromJson(response, LoginBean.class);
                    if (loginBean!=null){
                        List<String> ref = loginBean.getRef();
                        if (ref!=null&&ref.size()==2){
                            String usercode = ref.get(0);
                            String userName = ref.get(1)==null?"":ref.get(1);
                            if (TextUtils.isEmpty(userName)){
                                ToastUtil.showToast("登陆校验失败");
                                return;
                            }
                            SpUtil.putString(Login.this,ConstanceHeTai.user_code,usercode);
                            SpUtil.putString(Login.this,ConstanceHeTai.user_name,userName);

                            Intent intent = new Intent(getApplicationContext(), Login_choose.class);
                            startActivity(intent);
                        }

                    }

                }catch (Exception ex){
                    ex.printStackTrace();
                    ToastUtil.showToast("数据有误");
                }

            }
        });
    }

    //默认用户写入
    private void initdata() {
        //判断是否选择记住用户
        if (application.mSharedPreferences.getBoolean("LOGIN_ISCHECK", false)) {
            rem_pw.setChecked(true);
            //填写默认用户
            username.setText(application.mSharedPreferences.getString("LOGIN_USER_NAME", ""));
            pwd.setText(application.mSharedPreferences.getString("LOGIN_PASSWORD", ""));
        }

    }

    private void abLogin() {
        AbTask task = new AbTask();
        final AbTaskItem item = new AbTaskItem();
        item.setListener(new AbTaskObjectListener() {

            @Override
            public <T> void update(T entity) {
                AbDialogUtil.removeDialog(Login.this);
                Log.d("TAG", "登录执行完成");
                if (!isServerOk()) {
                    AbToastUtil.showToast(Login.this, R.string.isServerOk);
                    Intent intent = new Intent(getApplicationContext(), ServerSettings.class);
                    startActivity(intent);
                    return;
                }

                String susername = username.getText().toString();
                final String spwd = pwd.getText().toString();
                //必须输入用户名,密码可以不输(后续将改进为密码不可为空,android平台密码与windows平台密码分开)
                if (susername.isEmpty()) {
                    AbToastUtil.showToast(Login.this, R.string.toast_required_username);
                    return;
                }
                String urlString = "http://" + InstorageURL.SERVERURL + BaseUrl_New;
                String nameSpace = "http://service.test.com";
                String methodName = "userlogin";
                AbSoapParams params = new AbSoapParams();
                params.put("user", susername);
                params.put("spwd", spwd);
                mAbSoapUtil.call(urlString, nameSpace, methodName, params, new AbSoapListener() {
                    //获取数据成功会调用这里
                    @Override
                    public void onSuccess(int statusCode, String content) {
                        if (content != null) {
                            String userid = null;
                            String username = null;
                            String[] a = content.split(";");
                            for (int i = 0; i < a.length; i++) {
                                String[] id = a[0].split("=");
                                for (int m = 0; m < id.length; m++) {
                                    userid = id[2];
                                }

                                String[] name = a[1].split("=");
                                for (int m = 0; m < name.length; m++) {
                                    username = name[1];
                                }
                            }
                            if (userid.equals("anyType{}") || userid.equals("") || username.equals("anyType{}") || username.equals("")) {
                                AbToastUtil.showToast(Login.this, "用户名不存在或密码错误");
                                return;
                            } else if (userid.equals("password_error")) {
                                AbToastUtil.showToast(Login.this, "用户密码错误");
                                return;
                            }
                            if (rem_pw.isChecked()) {
                                //记住用户名,并且保存密码
                                SharedPreferences.Editor editor = application.mSharedPreferences.edit();
                                editor.putBoolean("LOGIN_ISCHECK", true);
                                editor.putString("LOGIN_USER_ID", userid);
                                editor.putString("LOGIN_USER_NAME", username);
                                editor.putString("LOGIN_PASSWORD", spwd);
                                editor.commit();
                            } else if (!application.mSharedPreferences.getString("LOGIN_PASSWORD", "").isEmpty()) {
                                SharedPreferences.Editor editor = application.mSharedPreferences.edit();
                                editor.putBoolean("LOGIN_ISCHECK", false);
                                editor.putString("LOGIN_USER_NAME", "");
                                editor.putString("LOGIN_PASSWORD", "");
                                editor.commit();
                            }
                            //记录当前用户名和编号
                            User u = new User(getApplicationContext());
                            u.login(userid, username);
                            AbToastUtil.showToast(Login.this, R.string.loginsuceed);
                            Intent intent = new Intent(getApplicationContext(), Login_choose.class);
                            startActivity(intent);
                        } else {
                            AbToastUtil.showToast(Login.this, R.string.sqlerrormsg);
                        }
                    }

                    // 失败，调用
                    @Override
                    public void onFailure(int statusCode, String content,
                                          Throwable error) {
                        AbToastUtil.showToast(Login.this, R.string.sqlerrormsg);
                    }

                    // 开始执行前
                    @Override
                    public void onStart() {
                        //显示进度框
                        //AbDialogUtil.showProgressDialog(Login.this, 0, "正在登录...");
                    }


                    // 完成后调用，失败，成功
                    @Override
                    public void onFinish() {
                        //移除进度框
                        AbDialogUtil.removeDialog(Login.this);
                    }

                });
            }

            @SuppressWarnings("unchecked")
            @Override
            public Integer getObject() {
                return -1;
            }
        });
        task.execute(item);
    }

    //用户登录
//    private void login() {
//        //服务器设置检测
//        if (!isServerOk()) {
//            AbToastUtil.showToast(Login.this, R.string.isServerOk);
//            Intent intent = new Intent(getApplicationContext(), ServerSettings.class);
//            startActivity(intent);
//            return;
//        }
//
//        String susername = username.getText().toString();
//        final String spwd = pwd.getText().toString();
//        //必须输入用户名,密码可以不输(后续将改进为密码不可为空,android平台密码与windows平台密码分开)
//        if (susername.isEmpty()) {
//            AbToastUtil.showToast(Login.this, R.string.toast_required_username);
//            return;
//        }
//        loadingDialog.loading(this);
//        //设置webservice的soap参数
//        TreeMap<String, String> properties = new TreeMap<String, String>();
//        properties.put("arg0", susername);
//        properties.put("arg1", spwd);
//        ToolSOAP.callService(InstorageURL.SERVERURL, InstorageURL.NAME_SPACE, "userlogin", properties, new ToolSOAP.WebServiceCallBack() {
//            @Override
//            public void onSucced(SoapObject result) {
//                loadingDialog.loadingfinish();
//                if (result != null) {
//                    SoapObject res = (SoapObject) result.getProperty(0);
//                    String userid = res.getProperty(0).toString();
//                    String username = res.getProperty(1).toString();
//                    if (userid.equals("anyType{}") || userid.equals("") || username.equals("anyType{}") || username.equals("")) {
//                        AbToastUtil.showToast(Login.this, R.string.errornameorpwd);
//                        return;
//                    } else if (userid.equals("password_error")) {
//                        AbToastUtil.showToast(Login.this, R.string.errorpwd);
//                        return;
//                    }
//                    //登录成功
//                    if (rem_pw.isChecked()) {
//                        //记住用户名,并且保存密码
//                        SharedPreferences.Editor editor = application.mSharedPreferences.edit();
//                        editor.putBoolean("LOGIN_ISCHECK", true);
//                        editor.putString("LOGIN_USER_ID", userid);
//                        editor.putString("LOGIN_USER_NAME", username);
//                        editor.putString("LOGIN_PASSWORD", spwd);
//                        editor.commit();
//                    } else if (!application.mSharedPreferences.getString("LOGIN_PASSWORD", "").isEmpty()) {
//                        SharedPreferences.Editor editor = application.mSharedPreferences.edit();
//                        editor.putBoolean("LOGIN_ISCHECK", false);
//                        editor.putString("LOGIN_USER_NAME", "");
//                        editor.putString("LOGIN_PASSWORD", "");
//                        editor.commit();
//                    }
//                    //记录当前用户名和编号
//                    User u = new User(getApplicationContext());
//                    u.login(userid, username);
//                    AbToastUtil.showToast(Login.this, R.string.loginsuceed);
//                    Intent intent = new Intent(getApplicationContext(), Login_choose.class);
//                    startActivity(intent);
//                } else {
//                    AbToastUtil.showToast(Login.this, R.string.sqlerrormsg);
//                }
//                //finish();//不结束当前
//            }
//
//            @Override
//            public void onFailure(String result) {
//                loadingDialog.loadingfinish();
//                AbToastUtil.showToast(Login.this, R.string.sqlerrormsg);
//                Log.v("tag", "err" + result);
//            }
//        });
//    }

    //是否设置了服务器地址
    private boolean isServerOk() {
        String server_url=    SpUtil.getString(Login.this,ConstanceHeTai.login_server_address);

        String server_code = SpUtil.getString(Login.this,ConstanceHeTai.login_server_code);

        if (server_url.isEmpty() || server_code.isEmpty()) {
            return false;
        }
        InstorageURL.SERVERURL = server_url;
        InstorageURL.SERVERCODE = server_code;
        return true;
    }

    public void toast(String msg) {
        AbToastUtil.showToast(Login.this, "msg");
    }

    //连续２次点返回才退出
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        // TODO Auto-generated method stub
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            exitBy2Click();
        }
        return false;
    }

    private static Boolean isExit = false;

    private void exitBy2Click() {
        Timer tExit = null;
        if (isExit == false) {
            isExit = true;
            AbToastUtil.showToast(Login.this, R.string.exitagain);
            tExit = new Timer();
            tExit.schedule(new TimerTask() {
                @Override
                public void run() {
                    isExit = false;
                }
            }, 2000);
        } else {
            finish();
        }
    }
    @Override
    public void onRequestPermissionsResult(int requestCode,   String[] permissions,   int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        EasyPermission.handleResult(this, requestCode, permissions, grantResults);//处理权限申请回调结果

    }
    @Override
    public void onBasicPermissionSuccess() {
        //服务器已设置则检查更新
        if (isServerOk()) {
            UpdateManager manager = new UpdateManager(Login.this);
            manager.checkUpdate(version_tv);
        }
    }

    @Override
    public void onBasicPermissionFailed() {
        //服务器已设置则检查更新
        if (isServerOk()) {
            UpdateManager manager = new UpdateManager(Login.this);
            manager.checkUpdate(version_tv);
        }
    }

    @Override
    public void onBasicPermissionFailedNeedRational() {
        //最好以对话框形式引导
        AlertDialog dialog = new AlertDialog.Builder(Login.this).setTitle("请前往应用授权设置中添加授权").setPositiveButton("去授权", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
                Uri uri = Uri.fromParts("package", Login.this.getPackageName(), null);
                intent.setData(uri);
                startActivityForResult(intent, 001);
            }
        }).setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                //服务器已设置则检查更新
                if (isServerOk()) {
                    UpdateManager manager = new UpdateManager(Login.this);
                    manager.checkUpdate(version_tv);
                }

            }
        }).show();

    }
}
